package com.SpringBoot.security.filter;

import com.SpringBoot.Util.JwtUtil;
import com.SpringBoot.Util.RedisService;
import com.SpringBoot.Util.Result;
import com.SpringBoot.security.MyUserDetails;
import com.fasterxml.jackson.databind.ObjectMapper;

import io.jsonwebtoken.Claims;
import jakarta.servlet.FilterChain;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.ServletException;
import lombok.Data;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Objects;


//权限认证过滤器
//@Component
//@EnableGlobalMethodSecurity(prePostEnabled = true)
@Data
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    //@Autowired
    private RedisService redisService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        // 兼容 Authorization: Bearer xxx
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7); // 去掉 "Bearer " 前缀
        }
        if(token == null || token.isEmpty()){
            filterChain.doFilter(request, response);
            return;
        }


        // 解析Token
        String userId = "";
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userId = claims.getSubject();
        } catch (Exception e) {
            response.getWriter().write(
                    new ObjectMapper().writeValueAsString(Result.error(403, "token非法"))
            );
            return;
        }

        // 获取用户信息
        MyUserDetails myUserDetails = redisService.getCacheObject("user:" + userId);
        if (Objects.isNull(myUserDetails)) {
            response.getWriter().write(
                    new ObjectMapper().writeValueAsString(Result.error(403, "登录过期"))
            );
            return;
        }

        // 放入 SecurityContext
        UsernamePasswordAuthenticationToken authenticationToken
                = new UsernamePasswordAuthenticationToken(myUserDetails, null, myUserDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        // 放行
        filterChain.doFilter(request, response);
    }
}

